package com.zl.pet.service.impl;

import com.zl.basic.exception.BusinessException;
import com.zl.basic.service.IBaiduAiAuditService;
import com.zl.basic.service.impl.BaseServiceImpl;
import com.zl.basic.util.*;
import com.zl.order.domain.OrderPetAcquisition;
import com.zl.order.mapper.OrderPetAcquisitionMapper;
import com.zl.org.domain.Employee;
import com.zl.org.domain.Shop;
import com.zl.org.mapper.EmpMapper;
import com.zl.org.mapper.ShopMapper;
import com.zl.pet.domain.Pet;
import com.zl.pet.domain.SearchMasterMsg;
import com.zl.pet.domain.SearchMasterMsgAuditLog;
import com.zl.pet.dto.MsgDto;
import com.zl.pet.mapper.PetMapper;
import com.zl.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.zl.pet.mapper.SearchMasterMsgMapper;
import com.zl.pet.query.SearchMasterMsgQuery;
import com.zl.pet.service.ISearchMasterMsgService;
import com.zl.user.domain.LoginInfo;
import com.zl.user.domain.User;
import com.zl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // 1.添加寻主消息
        LoginInfo logininfo = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);


        //2.审核
        Boolean textBoo = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + "," +
                searchMasterMsg.getName() + "," + searchMasterMsg.getAddress());

        Boolean imageBoo = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        //3.审核成功：修改寻主消息状态1
        if (textBoo && imageBoo){
            searchMasterMsg.setState(1);
            searchMasterMsg.setNote("审核成功！！！");

            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop!=null){
                searchMasterMsg.setShopId(nearestShop.getId());
            }

            searchMasterMsgMapper.update(searchMasterMsg);
                SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
                log.setMsgId(searchMasterMsg.getId());
                log.setState(1);
                log.setNote("审核成功！！！");
                searchMasterMsgAuditLogMapper.save(log);




        }else {
            //4.审核失败：修改寻主消息状态0
            searchMasterMsg.setNote("审核失败！！！,内容有非法字符");
            searchMasterMsgMapper.update(searchMasterMsg);


            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("审核失败！！！");
            searchMasterMsgAuditLogMapper.save(log);
            throw new BusinessException("审核失败，有非法字符，请重新提交！！！");
        }



    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        LoginInfo loginUser = LoginContext.getLoginUser(request);
        Employee employee = empMapper.loadByLogininfoId(loginUser.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        LoginInfo loginUser = LoginContext.getLoginUser(request);
        User user = userMapper.loadByLogininfoId(loginUser.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }



    @Override
    public void accept(MsgDto msgDto) {
        Long empId = msgDto.getHandler();
        Long msgId = msgDto.getMsgId();
        Long note = msgDto.getNote();


        //校验订单是否已经在处理中
        OrderPetAcquisition orderPetAcquisition =  orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (orderPetAcquisition!=null){
            throw new BusinessException("订单正在被处理中，请接取其他订单！！！");
        }
        // 创建宠物订单
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.save(pet);

        //创建收购单
        OrderPetAcquisition order =  buildOrder(pet,searchMasterMsg,empId);
        orderPetAcquisitionMapper.save(order);
        //发送邮件或者短信告知收购人在规定的时间去收购宠物
        System.out.println("你有新的宠物订单，请在规定时间内处理！！！");
    }

    private OrderPetAcquisition buildOrder(Pet pet, SearchMasterMsg msg, Long empId) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        order.setOrderSn(CodeGenerateUtils.generateOrderSn(pet.getUserId()));
        order.setDigest(msg.getTitle());
        long time = System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000;
        order.setLastcomfirmtime(new Date(time));
        order.setState(0);
        order.setPrice(new BigDecimal(msg.getPrice()));
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(empId);
        order.setSearchMasterMsgId(msg.getId());
        return order;

    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice().toString());
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }
}
